<?php
/*
$SNAME = session_name("JANSENSESSION");
if (isset($_COOKIE[$SNAME]) || isset($_GET[$SNAME])) {
$SID = isset($_COOKIE[$SNAME]) ? $_COOKIE[$SNAME] : $_GET[$SNAME];
session_id($SID);
} else {
$SID = session_id();
}

session_start();
setcookie(session_name(), session_id(), time()+3600*24*365, "/");
*/

require_once './include/common.inc.php';
//echo "<pre>";print_r($LEFT_MENU_ARY);exit;

checkLogin();
$postiondiv='<div class="position"><a href="index.php">首页</a> &gt; <span class="position"> 检视购物车 </span></div>';
$baner_img='<div class="bigtitle">检视购物车</div>';

$from_url = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $PHP_SELF;

$page_title = 'jans2en furniture - Container - Container';

getMyParam('act');
getMyParam('pid');
getMyParam('newpid');
getMyParam('inventoryid');
getMyParam('inventorytype');
getMyParam('intype');
getMyParam('fitemid');
getMyParam('fabid');
getMyParam('leaid');
getMyParam('js');
$intype = (int)$intype;

if ($act == 'add' && is_numeric($pid)) 
{
	getMyParam('addnum');
	!isset($inventoryid) && $inventoryid =0;

	$sql = "SELECT * FROM `product` WHERE `id`='$pid'";
	$product_info_ary = $db->get_one($sql);

	$cart = new cart();
	$have_set_ary = $cart->getData();


    $fabid=$fabid==""?0:$fabid;
	$leaid=$leaid==""?0:$leaid;
	//$id_str = $intype . '_' . $pid;
	$id_str = $intype . '_' . $pid . '_'. $fitemid.'_'. $fabid. '_'. $leaid;

	if (array_key_exists($id_str, $have_set_ary)) {
		/*echo "<script>alert('" . $rs['name'] . " have added.');history.back(1);</script>";*/
		echo "<script>alert('产品".$product_info_ary['code']."已经存在于购物车中！');</script>";		
		exit;
	}
	
	if(!empty($fitemid))
	{
		$sql = "SELECT upcharge from p_finish_item where id = ".$fitemid;
		$fitem_upcharge = $db->get_one($sql);
	}
	$sql = "SELECT `special_price` FROM `product_inventory` WHERE `product_id`='$pid' AND `inventory_id`='$inventoryid'";
	$tmp_ary = $db->get_one($sql);
	$sp = $tmp_ary['special_price'];
	!$sp && $sp=0;
	$code = $product_info_ary['code'];
	$name = $product_info_ary['namezh'];
	
	$price = getPrice($jansen_type, $inventorytype, $product_info_ary, $sp);
	$upcharge = $product_info_ary['upcharge'];
	if( ! empty($newpid))
	{
		$new_sql = "SELECT * FROM `product` WHERE `id`='$newpid'";
		$new_product_info_ary = $db->get_one($new_sql);

		$new_sql = "SELECT `special_price` FROM `product_inventory` WHERE `product_id`='$pid' AND `inventory_id`='$inventoryid'";
		$new_tmp_ary = $db->get_one($new_sql);
		$new_sp = $new_tmp_ary['special_price'];
		!$new_sp && $new_sp=0;
		$price = getPrice($jansen_type, $inventorytype, $new_product_info_ary, $new_sp);
		$code = $new_product_info_ary['code'];
		$upcharge = $new_product_info_ary['upcharge'];
	}
	else
	{
		if(!empty($fabid) OR !empty($leaid))
		{
			$price = 0;
		}
	}
	if(! empty($price) AND !empty($fitem_upcharge) AND in_array($fitem_upcharge['upcharge'],array('Yes','super')))
	{
		$price += $upcharge; 
	}

	$cart = new cart();
	$cart->addOne($pid,$code, $name, $price, $product_info_ary['cbm'], $product_info_ary['cuft'],$fitemid, $inventoryid,$fabid,$leaid);

	if (is_numeric($addnum) && $addnum>0) {
		//$cart->modifyCount($inventoryid . '_' . $pid, $addnum);
		$cart->modifyCount($id_str, $addnum);
	}

	if ($js) {
		echo "<script>alert('产品已加到购物车。');</script>";
	}

	saveCart($db, $jansen_uid, $cart);


}

if ($act == 'adddate' && is_array($_POST['p_num'])) {

	foreach ($_POST['p_num'] as $k=>$v) {
		if (is_numeric($v) && $v>0) {
			$pid_ary[] = $k;
		}
	}
	if (!empty($pid_ary)) {
		$pid_str = implode(",", $pid_ary);
		$cart = new cart();
		$have_set_ary = $cart->getData();

		$sql = "SELECT `product_id`, `special_price` FROM `product_inventory` WHERE `product_id` IN (" . $pid_str . ") AND `inventory_id`='$inventoryid'";
		$query = $db->query($sql);
		while($rs = $db->fetch_array($query)) {
			$sp_ary[$rs['product_id']] = $rs['special_price'];
		}

		$sql = "SELECT * FROM `product` WHERE `id` IN (" . $pid_str . ")";
		$query = $db->query($sql);

		while($rs = $db->fetch_array($query)) {
			$id_str = $intype . '_' . $rs['id'];
			if (($inventorytype == 1 || $inventorytype == 2 )&& array_key_exists($id_str, $have_set_ary)) {
				echo "<script>alert('Item " . $rs['code'] . " 产品已经存在于购物车 !');</script>";
				exit;
			}

			$sp = isset($sp_ary[$rs['id']]) ? $sp_ary[$rs['id']] : 0;
			$price = getPrice($jansen_type, $inventorytype, $rs, $sp);
			//echo $price;exit;
			$data[] = array('id'=>$rs['id'], 'name'=>$rs['name'], 'price'=>$price, 'cbm'=>$rs['cbm'], 'cuft'=>$rs['cuft'], 'count'=>$_POST['p_num'][$rs['id']], 'intype'=>$intype);
		}
		//echo "<pre>";print_r($data);exit;
		$cart = new cart();
		$cart->addData($data);

		saveCart($db, $jansen_uid, $cart);

		if ($js) {
			echo "<script>alert('产品已加到购物车。');parent.document.getElementById('addtocontentiframe').src='';parent.location.href='" . $from_url . "';</script>";
			exit;
		}
	}
}

if ($act == 'clearall') {
	$cart = new cart();
	$cart->emptyAll();
	@saveCart($db, $jansen_uid, "");
}

if ($act == 'delone') { 
	$cart = new cart();
	$cart->emptyOne($pid);
	//echo $cart->getTotalCost();exit;
	if ($cart->getSortCount() == 0) {
		@saveCart($db, $jansen_uid, "");
	} else {
		@saveCart($db, $jansen_uid, $cart);
	}
}

if ($act == 'change') {
	getMyParam('selFinish');
	getMyParam('cart_qty');
	getMyParam('selfab');
	getMyParam('new_key');
	//echo "<pre>";print_r($cart_qty);
	$cart = new cart();

	foreach ($selFinish as $k=>$v) {
        $new_id = $new_key[$k];
		if (!is_numeric($cart_qty[$k]) && trim($cart_qty[$k])!='') continue;
		else if($cart_qty[$k] <= 0 || trim($cart_qty[$k])=='') 
		{
			$cart->emptyOne($new_id);
		} 
		else
		{
			$aryTmp = explode('_',$k);
			$fab_id = $lea_id = 0;
			if(substr($selfab[$k],0,1) == 'l')
			{
				$lea_id = str_replace('l_', '', $selfab[$k]);
				$fab_id = 0;
			}
			else if(substr($selfab[$k],0,1) == 'f')
			{
				$fab_id = str_replace('f_', '' ,$selfab[$k]);
				$lea_id = 0;
			}
	    	$aryTmp[2]=$v?$v:0;
	    	$aryTmp[3]=$fab_id;
	    	$aryTmp[4]=$lea_id;
            if(array_key_exists($new_id, $selFinish) AND $k != $new_id)
            {
                $cart_qty[$new_id] += $cart_qty[$k];
                $cart->modifyCount($new_id, $cart_qty[$k]);
                unset($selFinish[$k]);
                $cart->emptyOne($k);
                continue;
            }

			if($v != $fitemid[$k] || $selfab[$k]!=$fabid[$k] || $sellea[$k]!=$leaid[$k])
			{
			   $cart->modifyAllKey($new_id,$v,$fab_id,$lea_id,$cart_qty[$k]);
			}
		}		
	}
	

	if ($cart->getSortCount() == 0) {
		@saveCart($db, $jansen_uid, "");
	} else {
		@saveCart($db, $jansen_uid, $cart);
	}
}


$cart = new cart(); 
$info_ary = $cart->getData();
$total_qty = $cart->getSortCount();
$total_cost = $cart->getTotalCost();

//echo "<pre>";print_r($cart);
//setcookie('jansen_total_qty', $total_qty, time()+3600*24*365, "/");

$all_product_info_ary = array();
foreach ($info_ary as $pid=>$vv) {
	$code_ary[] = $vv['code'];
}
//echo "<pre>"; print_r($pid_ary);
$js_id_ary = array();

if (!empty($code_ary)) 
{
	$code_str = implode("','", $code_ary);
	$sql = "SELECT `id`, `code`, `namezh`,`pcode`,`fabric_cat`,`leather_cat`, `small_pic`, `pic`, `cbm`, `cuft`, `finish_id`,`fabric_flag`,`leather_flag` FROM `product` WHERE code IN ('" . $code_str . "')";
	$query = $db->query($sql);
	while($rs = $db->fetch_array($query)) {
		//$rs['cbm'] = sprintf("%0.2f", $rs['cbm']);
		//$rs['cuft'] = sprintf("%0.2f", $rs['cuft']);
		$all_product_info_ary[$rs['code']] = $rs;
		
		$id_ary[] = $rs['id'];
	}
	$pid_str = implode(",", $id_ary);

	$sql = "SELECT `product_id`, `inventory_id`, `qty` FROM `product_inventory` WHERE `product_id` IN (" . $pid_str . ") AND `qty`>=0";
	$query = $db->query($sql);
	while($rs = $db->fetch_array($query)) {
		$product_qty_ary[$rs['product_id']] = $rs['qty'];
		$js_id_ary[] = "'" . $rs['inventory_id'] . '_' . $rs['product_id'] . "'";
	}

}

$js_id_ary_str = !empty($js_id_ary) ? "new Array(" . implode(',', $js_id_ary) . ")" : "new Array()";

if ($jansen_type == 1) {
	$money_type = " HKD";
} else {
	$money_type = " 美金";
}

$sql = "SELECT * FROM `user` WHERE `id`='$jansen_uid'";
$user_info_ary = $db->get_one($sql);

$sql = "SELECT * FROM `inventory`";
$query = $db->query($sql);
while($rs = $db->fetch_array($query)) {
	$location_info_ary[$rs['id']] = $rs['name'];
}

$total_qty2 = $total_cbm = $total_cuft = 0;

$index_ary = array();
$finish_cate = array();
$leather_cate = array();
$fabric_cate = array();

foreach ($info_ary as $k=>$v) {
  //���ط�
	$location = $v['intype'] == 0 ? 'Products' : $location_info_ary[$v['intype']];

	$js_str = $v['intype'] == 0 ? '' : '<input type="hidden" name="inventory_qty[' . $k . ']" value="' . $product_qty_ary[$v['id']] . '">';
	if (trim($all_product_info_ary[$v['code']]['small_pic']) == "" || !file_exists("./zh/attachments/" . $all_product_info_ary[$v['code']]['small_pic'])) {
		$all_product_info_ary[$v['code']]['small_pic'] = 'no_40.gif';
	}
	
    $product = $db->get_one('select small_pic from product where id = '.$v['id']);
    
	$index_ary[$k] = array(
		'id' => $v['id'],
		'code' => $v['code'],
		'key' => $k,
		'location' => $location,
		'name' => $v['name'],
		'small_pic' => $product['small_pic'],
		'cbm' => $all_product_info_ary[$v['code']]['cbm'],
		'cuft' => $all_product_info_ary[$v['code']]['cuft'],
		'price' => $v['price'],
		'count' => $v['count'],
		'cost' => $v['cost'],
		'intype' => $v['intype'],
		'finish_id' => $all_product_info_ary[$v['code']]['finish_id'],
		'fitemid' => $v['fitemid'],
		'fabric_cat'=> $all_product_info_ary[$v['code']]['fabric_cat'],
		'fabid'=> $v['fabid'],
		'leather_cat'=>$all_product_info_ary[$v['code']]['leather_cat'],
		'leaid'=> $v['leaid'],
		'js_str' => $js_str,
		'js_str' => $js_str,
		'fabric_flag' => $all_product_info_ary[$v['code']]['fabric_flag'],
		'leather_flag' => $all_product_info_ary[$v['code']]['leather_flag'],
	);
 /* print_r($index_ary[$v['intype'] . $all_product_info_ary[$v['code']]['code'].'_'.$v['fitemid']]);
   echo "<br/><br/>";*/
	$total_qty2 += $v['count'];
	$total_cbm += $v['count']*$all_product_info_ary[$v['code']]['cbm'];
	$total_cuft += $v['count']*$all_product_info_ary[$v['code']]['cuft'];
	
	$finish_cate[] = $index_ary[$k]['finish_id'];
	$leather_cate[] = $index_ary[$k]['leather_cat'];
	$fabric_cate[] = $index_ary[$k]['fabric_cat'];
}
ksort($index_ary);

$leathers_item_ary=array();
//$in_str = empty($leather_cate)?'':' where cat_id in('.implode(',',$leather_cate).')';
$sql = "SELECT * FROM `p_leather` ORDER BY `seq`";
$query = $db->query($sql);
$rsl="";
while($rsl = $db->fetch_array($query)) 
{  	  
	$leathers_item_ary[$rsl['id']]=$rsl;
   //$leathers_item_ary[$rsl['cat_id']][]=$rsl;	   
}

$fabrics_item_ary=array();
//$in_str = empty($fabric_cate)?'':' where cat_id in('.implode(',',$fabric_cate).')';
$sql = "SELECT * FROM `p_fabric` ORDER BY `seq`";
$query = $db->query($sql);
$rsf="";
while($rsf = $db->fetch_array($query)) 
{	
	 $fabrics_item_ary[$rsf['id']]=$rsf;		
	 //$fabrics_item_ary[$rsf['cat_id']][]=$rsf;	
}

$finish_item_ary=array();
$in_str = empty($finish_cate)?'':' where sid in('.implode(',',$finish_cate).')';
$sql = "SELECT * FROM `p_finish_item` $in_str ORDER BY `orderindex`";
$query = $db->query($sql);
$rsf="";
while($rsf = $db->fetch_array($query)) 
{			
	 $finish_item_ary[$rsf['sid']][]=$rsf;	
}

$total_cost  = number_format($total_cost, 2, '.', ',');
$total_cbm  = number_format(round($total_cbm), 2, '.', ',');
$total_cuft  = number_format(round($total_cuft), 2, '.', ',');
$jansen_total_qty1 = $total_qty;
$top_out = "&nbsp;&nbsp;" . $total_cbm . " CBM&nbsp;&nbsp;" . $total_cuft . " CUFT&nbsp;&nbsp;" . $total_cost . " $money_type";
/*if ($jansen_total_qty1 == 0) {
$top_out = '';
}*/

//$LEFT_MENU_ARY = $LEFT_MENU_IN_ARY;
//$jansen_total_qty1 $total_item
//$user_status = <<<EOT
//                <td  height="23"><img src="./css/images/top_nav_cart.jpg" alt="Cart:" name="jf_cart_dispay_cart" width="50" height="23" id="jf_cart_dispay_cart"></td>
//                <td align="left" valign="top" height="20" class="cartAreaValues"><div><img name="" src="./images/spacer.gif" width="1" height="5" alt=""></div>                   
//                  <span class="item_number">:  $top_out</span> </td>
//                <td width="10" ></td>
//                <td ><a href="cart_view.php" ><img src="./css/images/top_nav_view_cart.jpg" alt="View Cart" name="jf_cart_dispay_view_cart" width="75" height="23" border="0" id="jf_cart_dispay_view_cart"></a></td>
//                <td width="10" ></td>
//                <td width="51" ><img  src="./css/images/top_nav_wishlist.jpg" alt="Wishlist:" name="jf_cart_dispay_wishlist" width="77" height="23" id="jf_cart_dispay_wishlist"></td>
//                <td align="left" valign="top" height="20" class="cartAreaValues"><div><img name="" src="./images/spacer.gif" width="1" height="5" alt=""></div>
//                   
//                  <span class="item_number">: $jansen_wishlist_qty1 $wishlist_item</span> </td>
//                <td width="10" ></td>
//                <td width="58" ><a href="wishlist_view.php" ><img src="./css/images/top_nav_view_wishlist.jpg" alt="View List" name="jf_cart_dispay_view_list" width="106" height="23" border="0" id="jf_cart_dispay_view_list"></a></td>
//                <td width="10" ></td>
//                <td width="68" ><a href="login.php?action=logout" ><img src="./css/images/top_nav_dealerlogout.jpg"  alt="Dealer Logout" name="jf_cart_dispay_dealer_logout" width="100" height="23" border="0" id="jf_cart_dispay_dealer_logout"></a></td>
//EOT;

require_once PrintEot('header');
require_once PrintEot('cart_view');
require_once PrintEot('footer');

?>
